<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------
namespace app\adminapi\logic\user;

use app\common\enum\user\AccountLogEnum;
use app\common\enum\user\UserTerminalEnum;
use app\common\logic\AccountLogLogic;
use app\common\logic\BaseLogic;
use app\common\model\finance\PaymentRecord;
use app\common\model\user\User;
use app\common\model\user\UserGroup;
use think\facade\Db;

/**
 * 用户逻辑层
 * Class UserLogic
 * @package app\adminapi\logic\user
 */
class UserLogic extends BaseLogic
{

    /**
     * @notes 用户详情
     * @param int $userId
     * @return array
     * @author 段誉
     * @date 2022/9/22 16:32
     */
    public static function detail(int $userId): array
    {
        $field = [
            'id', 'sn', 'account', 'nickname', 'avatar', 'real_name',
            'sex', 'mobile', 'create_time', 'login_time', 'channel',
            'user_money', 'card_bin', 'card_free', 'card_sum', 'email'
        ];

        $user = User::where(['id' => $userId])->field($field)
            ->findOrEmpty();
//        $user->hidden(['channel']);
//        $user['channel'] = UserTerminalEnum::getTermInalDesc($user['channel']);
        $user->sex = $user->getData('sex');
        return $user->toArray();
    }


    /**
     * @notes 更新用户信息
     * @param array $params
     * @return User
     * @author 段誉
     * @date 2022/9/22 16:38
     */
    public static function setUserInfo(array $params)
    {
        return User::update([
            'id' => $params['id'],
            $params['field'] => $params['value']
        ]);
    }


    /**
     * @notes 调整用户余额
     * @param array $params
     * @return bool|string
     * @author 段誉
     * @date 2023/2/23 14:25
     */
    public static function adjustUserMoney(array $params)
    {
        Db::startTrans();
        try {
            $user = UserGroup::find($params['group_id']);
            if (AccountLogEnum::INC == $params['action']) {
                //调整可用余额
                if ($params['num'] > 0) {
                    $user->user_money += $params['num'];
                    $user->user_money_total += $params['num'];
                    $user->save();
                    
                    // 根据操作类型选择不同的change_type
                    $changeType = AccountLogEnum::UM_INC_ADMIN;
                    if (isset($params['change_type']) && $params['change_type'] == 'rebate') {
                        $changeType = AccountLogEnum::UM_INC_REBATE;
                    }
                    
                    //记录日志
                    AccountLogLogic::add(
                        $user->id,
                        $changeType,
                        AccountLogEnum::INC,
                        $params['num'],
                        $params['payment_id'] ?? '',
                        $params['remark'] ?? '',
                        ['admin_id'=>$params['admin_id']]
                    );
                    //充值后删除低余额通知消息
                    Db::name('userNotis')->where(['group_id' => $params['group_id'], 'type' => 1])
                        ->delete();
                }

                //充值后修改存款记录状态
                if (isset($params['payment_id']) && !empty($params['payment_id'])) {
                    PaymentRecord::where('id', $params['payment_id'])->update([
                        'deposit_amount' => $params['num'],
                        'status' => ($params['num'] > 0) ? 4 : 2,
                        'approval_user_id' => $params['admin_id'],
                        'approval_time' => date('Y-m-d H:i:s'),
                        'approval_remarks' => $params['approval_remarks'] ?? ''
                    ]);
                }

            } else {
                $user->user_money -= $params['num'];
                $user->save();
                //记录日志
                AccountLogLogic::add(
                    $user->id,
                    AccountLogEnum::UM_DEC_ADMIN,
                    AccountLogEnum::DEC,
                    $params['num'],
                    '',
                    $params['remark'] ?? '',
                    ['admin_id'=>$params['admin_id']]
                );
            }

            Db::commit();
            return true;

        } catch (\Exception $e) {
            Db::rollback();
            return $e->getMessage();
        }
    }

}